<template>
  <div class="divStyle">
    <div class="treeStyle">
      <el-row class="rowNavStyle">
        <el-col :span="24" class="colNavStyle">
          <menuButton
            @addDepartmentKey="addClick"
            @editDepartmentKey="editClick"
            @deleteDepartmentKey="deleteClick"
            helper-path="pages/a2bdda"
          ></menuButton>
        </el-col>
      </el-row>
      <div>
        <el-tree
          style="max-width: 600px"
          :data="departmentList"
          default-expand-all
          :highlight-current="true"
          :expand-on-click-node="false"
          :check-strictly="true"
          :current-node-key="defaultSelectKey"
          v-loading="treeLoading"
          @node-click="handleClick"
          node-key="key"
          ref="departmentTree"
        >
          <template #default="{ node, data }">
            <div class="custom-node">
              <el-icon color="#67C23A" v-if="data.disabled">
                <Histogram
              /></el-icon>
              <el-icon color="#67C23A" v-if="data.disabled === false">
                <Memo
              /></el-icon>
              <span>&nbsp;{{ node.label }}</span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="userStyle">
      <el-table
        :data="tableData"
        stripe
        :border="true"
        row-key="roleId"
        v-loading="loading"
        default-expand-all
      >
        <el-table-column type="selection" width="55" />
        <!-- 动态列 -->
        <el-table-column
          show-overflow-tooltip
          v-for="itme in columns"
          :key="itme.fieldEnName"
          :prop="itme.fieldEnName"
          :label="itme.fieldCnName"
          :min-width="itme.fieldWidth"
          :sortable="itme.fieldSortable"
          :align="itme.fieldAlign"
        >
          <template v-if="itme.fieldSlot === 'sexSlot'" #default="sexSlot">
            <el-tag v-if="sexSlot.row.sex == 1" type="primary">男</el-tag>
            <el-tag v-if="sexSlot.row.sex == 2" type="danger">女</el-tag>
          </template>
          <template v-else-if="itme.fieldSlot === 'isOpen'" #default="isOpen">
            <el-switch
              :before-change="switchClick"
              v-model="isOpen.row.isOpen"
              class="ml-2"
              inline-prompt
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
              active-text="开启中"
              inactive-text="关闭中"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="userName"
          label="用户名称"
          align="center"
          width="100"
        />
        <el-table-column prop="corporationName" label="所属公司" />
        <el-table-column
          prop="departmentName"
          label="所在部门"
          align="center"
          width="150"
        />
        <el-table-column prop="age" label="年龄" align="center" width="80">
          <template #default="model">
            <el-tag v-if="model.row.age >= 40" type="warning">{{
              model.row.age
            }}</el-tag>
            <el-tag v-else-if="model.row.age <= 20" type="success">{{
              model.row.age
            }}</el-tag>
            <el-tag v-else>{{ model.row.age }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" align="center" width="80">
          <template #default="model">
            <el-tag v-if="model.row.sex == 1" type="primary">男</el-tag>
            <el-tag v-if="model.row.sex == 2" type="danger">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="isOpen"
          label="是否使用"
          align="center"
          width="100"
        >
          <template #default="model">
            <el-switch
              :before-change="switchClick"
              v-model="model.row.isOpen"
              class="ml-2"
              inline-prompt
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
              active-text="开启中"
              inactive-text="关闭中"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          width="150"
        /> -->
        <el-table-column label="操作" width="375">
          <template #default="scope">
            <dataRowButton
              :model="scope.row"
              @editUserKey="handleEdit(scope.row)"
              @setUserRoleKey="setUserRoleClick(scope.row)"
              @openUserKey="enableClick(scope.row)"
              @closeUserKey="closeClick(scope.row)"
            ></dataRowButton>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <addOrEdit
    :isVisibles="isVisibles"
    :modelData="departmentModel"
    :dialogTitle="dialogTitle"
    @closeBnt="colosDialog"
  ></addOrEdit>
  <addOrEditVue
    :isVisibles="isUserVisibles"
    :modelData="userModel"
    :dialogTitle="dialogTitle"
    @closeBnt="colosUserDialog"
  ></addOrEditVue>
  <setUserRole
    :isVisibles="isDrawerVisibles"
    :modelData="userModel"
    :dialogTitle="dDrawerTitle"
    @closeBnt="colosDrawerClick"
  ></setUserRole>
</template>
<script lang="ts" setup>
import {
  deleteById,
  getAllCorporationDepartmentList,
  getDepartmentUserList,
} from "@/api/department";
import { treeOutPut } from "@/model/public/treeModel";
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { SysUser, SysUserOutPut } from "@/model/user/user";
import addOrEdit from "../department/addOrEdit.vue";
import { SysDepartment } from "@/model/department/department";
import { setUserIsOpen } from "@/api/user";
import { UpdateIsOpenInPut } from "@/model/public/public";
import addOrEditVue from "../user/addOrEdit.vue";
import setUserRole from "../user/setUserRole.vue";
import menuButton from "@/components/menuButton.vue";
import { useUserStore } from "@/store/user";
import dataRowButton from "@/components/dataRowButton.vue";
import { GetMenuColsByMenuId } from "@/api/publicTool";

//初始加载dom
onMounted(() => {
  getAllCorporationDepartmentListMsg();
  // getDepartmentUserListMsg();
  GetMenuColsByMenuIdMsg();
});
//等待加载
const loading = ref(true);
//定义列
const columns = ref();
const treeLoading = ref(true);
const userStore = useUserStore();
//table数据
const tableData = ref<SysUserOutPut[]>([]);
//点击树形节点值
const checkedKeys2 = ref<SysDepartment[]>([]);
//默认选择节点
const defaultSelectKey = ref<string>(userStore.corporationKey);
//公司key
const corporationKey = ref<string>(userStore.corporationKey);
//控制弹出层显隐
const isVisibles = ref<boolean>(false);
//弹出层标题
const dialogTitle = ref<string>();

//控制弹出层显隐
const isUserVisibles = ref<boolean>(false);
//弹出层标题
const dialogUserTitle = ref<string>();
//控制抽屉显隐
const isDrawerVisibles = ref<boolean>(false);
//抽屉标题
const dDrawerTitle = ref<string>();

//人员模型数据
const userModel = reactive<SysUser>({
  UserId: "",
  CorporationKey: "",
  Age: 0,
  Sex: "1",
  DepartmentId: "",
  UserName: "",
  Password: "",
  IsOpen: true,
});

//部门模型数据
const departmentModel = reactive<SysDepartment>({
  Id: "",
  Pid: "",
  DepartmentName: "",
  Sort: 1,
  CorporationKey: "",
});
//设置用户是否启用输入模型
const updateUserIsOpenInPut = reactive<UpdateIsOpenInPut>({
  Keys: [],
  IsOpen: false,
});

//部门数据
const departmentList = ref<treeOutPut[]>([]);
const getAllCorporationDepartmentListMsg = function () {
  getAllCorporationDepartmentList()
    .then(({ data, code }) => {
      if (code == 200) {
        departmentList.value = data;
        handleClick(data[0]);
      }
      treeLoading.value = false;
    })
    .catch(() => {
      treeLoading.value = false;
    });
};
//菜单列
const GetMenuColsByMenuIdMsg = async () => {
  columns.value = await GetMenuColsByMenuId();
  if (columns.value.length > 1) {
    getDepartmentUserListMsg();
  } else {
    columns.value = [];
  }
};
//获取部门下的用户数据
const getDepartmentUserListMsg = async () => {
  getDepartmentUserList({
    id: checkedKeys2.value[0]?.Id,
    corporationKey: corporationKey.value,
  })
    .then(({ data, code }) => {
      if (code == 200) {
        tableData.value = data;
      }
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

//树点击事件
function handleClick(node: treeOutPut) {
  checkedKeys2.value = [];
  if (node.pKey != null) {
    departmentModel.DepartmentName = node.label;
    departmentModel.Id = node.key;
    departmentModel.Pid = node.pKey;
    departmentModel.Sort = node.sort;
    departmentModel.CorporationKey = node.corporationKey;
    checkedKeys2.value.push(departmentModel);
    corporationKey.value = node.corporationKey;
  } else {
    corporationKey.value = node.key;
  }
  getDepartmentUserListMsg();
}

//新增
const addClick = function () {
  const model = checkedKeys2;
  if (model.value.length > 0) {
    addOrEditMethod(model.value[0], true);
  } else {
    ElMessage({
      message: "请选择节点",
      type: "warning",
    });
  }
};

//编辑
const editClick = function () {
  if (checkedKeys2.value.length == 0) {
    ElMessage({
      message: "请选择部门进行编辑",
      type: "warning",
    });
  } else if (checkedKeys2.value.length > 1) {
    ElMessage({
      message: "只能选择一条数据进行编辑",
      type: "warning",
    });
  } else {
    if (checkedKeys2.value[0].Pid === "") {
      ElMessage({
        message: "不能编辑公司,请选择部门进行编辑",
        type: "warning",
      });
    } else addOrEditMethod(checkedKeys2.value[0], false);
  }
};

//新增或编辑方法
const addOrEditMethod = function (model: SysDepartment, isAdd: boolean) {
  if (isAdd) {
    departmentModel.Pid = model == undefined ? corporationKey.value : model.Id;
    departmentModel.Id = "";
    departmentModel.DepartmentName = "";
    departmentModel.Sort = 1;
  } else {
    departmentModel.Id = model.Id;
    departmentModel.Pid = model.Pid.length === 0 ? model.Id : model.Pid;
    departmentModel.DepartmentName = model.DepartmentName;
    departmentModel.Sort = model.Sort;
  }
  departmentModel.CorporationKey =
    model == undefined ? corporationKey.value : model.CorporationKey;
  dialogTitle.value = isAdd ? "新增部门" : "编辑部门";
  isVisibles.value = true;
};

//删除
const deleteClick = function () {
  if (checkedKeys2.value.length == 0) {
    ElMessage({
      message: "请选择部门删除",
      type: "warning",
    });
  } else if (checkedKeys2.value.length > 1) {
    ElMessage({
      message: "只能选择一条数据进行删除",
      type: "warning",
    });
  } else {
    if (checkedKeys2.value[0].Pid === "") {
      ElMessage({
        message: "不能删除公司,请选择部门删除",
        type: "warning",
      });
    } else {
      var title =
        "你确定要删除部门[" + checkedKeys2.value[0].DepartmentName + "]吗？";
      ElMessageBox.confirm(title, "提示消息", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteById({
            id: checkedKeys2.value[0]?.Id,
          }).then(({ data, code, msg }) => {
            if (code == 200) {
              ElMessage({
                message: msg,
                type: "success",
              });
              getAllCorporationDepartmentListMsg();
            }
          });
        })
        .catch(() => {
          //取消
        });
    }
  }
};

//关闭弹出层
const colosDialog = function () {
  checkedKeys2.value = [];
  getAllCorporationDepartmentListMsg();
  getDepartmentUserListMsg();
  isVisibles.value = false;
};

//关闭弹出层
const colosUserDialog = function () {
  getDepartmentUserListMsg();
  isUserVisibles.value = false;
};

//禁止点页面的滑块
const switchClick = function () {
  return new Promise((_, reject) => {
    return reject(new Error("Error"));
  });
};

//设置用户角色事件
const setUserRoleClick = function (model: SysUserOutPut) {
  if (model.corporationKey === "" || model.corporationKey === undefined) {
    ElMessage({
      message: "公司不能为空",
      type: "warning",
    });
    return;
  }

  dDrawerTitle.value = "设置用户【" + model.userName + "】的角色";
  isDrawerVisibles.value = true;
  userModel.CorporationKey = model.corporationKey;
  userModel.UserId = model.userId;
};

//关闭抽屉
const colosDrawerClick = function () {
  isDrawerVisibles.value = false;
};

//行内编辑事件
const handleEdit = function (model: SysUserOutPut) {
  addOrEditUser(model, false);
};

//关闭
const closeClick = function (model: SysUserOutPut) {
  setIsOpen(false);
  updateUserIsOpenInPut.Keys = [];
  updateUserIsOpenInPut.Keys.push(model.userId);
  updateUserIsOpenInPut.IsOpen = false;
};

//启用
const enableClick = function (model: SysUserOutPut) {
  setIsOpen(true);
  updateUserIsOpenInPut.Keys = [];
  updateUserIsOpenInPut.Keys.push(model.userId);
  updateUserIsOpenInPut.IsOpen = true;
};

//设置用户启用状态
const setIsOpen = function (isOpen: boolean) {
  var title = isOpen
    ? "你确认要开启选中用户，开启后用户将可以使用？"
    : "你确认要关闭选中用户，关闭后用户将停用！";
  ElMessageBox.confirm(title, "提示消息", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      setUserIsOpen(updateUserIsOpenInPut).then(({ data, code, msg }) => {
        if (code == 200) {
          getDepartmentUserListMsg();
          ElMessage({
            message: msg,
            type: "success",
          });
        }
      });
    })
    .catch(() => {
      //取消
    });
};

//新增或编辑方法
const addOrEditUser = function (model: SysUserOutPut, isAdd: boolean) {
  if (isAdd) {
    userModel.UserId = "";
    userModel.CorporationKey = "";
    userModel.Age = 0;
    userModel.Sex = "1";
    (userModel.DepartmentId = ""),
      (userModel.UserName = ""),
      (userModel.Password = ""),
      (userModel.IsOpen = true);
  } else {
    userModel.UserId = model.userId;
    userModel.CorporationKey = model.corporationKey;
    userModel.Age = model.age;
    userModel.Sex = model.sex.toString();
    (userModel.DepartmentId = model.departmentId),
      (userModel.UserName = model.userName),
      (userModel.Password = model.password),
      (userModel.IsOpen = model.isOpen);
  }
  dialogUserTitle.value = isAdd ? "新增用户" : "编辑用户";
  isUserVisibles.value = true;
};
</script>
<style scoped>
.divStyle {
  display: flex;
}
.treeStyle {
  border: 1px solid #00152914;
  box-shadow: 0 1px 4px #00152914;
  margin-bottom: 3px;
  width: 300px;
  height: 85vh;
  overflow-y: auto;
}
.treeTop {
  height: 50px;
  border: 1px solid #00152914;
  box-shadow: 0 1px 4px #00152914;
  margin-bottom: 3px;
  padding-left: 20px;
  align-items: center;
  display: flex;
}
.userStyle {
  border: 1px solid #00152914;
  box-shadow: 0 1px 4px #00152914;
  margin-bottom: 3px;
  margin-left: 3px;
  width: 100%;
  height: 85vh;
  overflow-y: auto;
}
</style>